// 引入构造函数
import Schema from "async-validator"
import {
  addressDetail,
  updateAddress,
  saveAdd
} from "../../../../api/address"
var QQMapWX = require("../../../../libs/qqmap-wx-jssdk")
Page({
  data: {
    // 方便数据的双向绑定
    "name": "", //收货人
    "phone": "", //手机号码
    "provinceName": "", //省
    "provinceCode": "", //省编码
    "cityName": "", //市
    "cityCode": "", //市编码
    "districtName": "", //区
    "districtCode": "", //市编码
    "address": "", //详细地址
    "fullAddress": "", //完整地址
    "isDefault": false, // 是否是默认地址
  },
  async onLoad(option) {
    // 实例化API核心类
    this.qqmapsdk = new QQMapWX({
      key: 'JHIBZ-TCGLZ-3Y3XF-7J4OW-FTLUO-RJFT5'
    });

    if (option.id) {
      // 查询回调api调用
      const {data} = await addressDetail(option.id)
      this.setData({
       ...data,
        id: option.id
      })
    }
  },
  // 保存收货地址
  async saveAddrssForm() {
    // 修改
    if (this.data.id) {
      const {
        message
      } = await updateAddress(this.data)
      wx.showToast({
        title: "修改地址" + message,
      })
      wx.navigateBack()
      
    } else {
      const {provinceName,cityName,districtName,isDefault} = this.data
      const params = {...this.data,fullAddress: provinceName + cityName + districtName,isDefault: isDefault ? 1 : 0}
      const {valid}=await this.validatorAddress(params)
      if(!valid)return 
      // 新增地址
      const res = await saveAdd(params);
      if (res.code === 200) {
        wx.showToast({
          title: '新增收获地址成功',
        })
        wx.navigateBack()
      }
    }
  },
  // 对新增参数进行验证
  validatorAddress(params){
    //收货人验证  手机号
    const nameRegExp='^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneRegExp=`^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$`

    const rules={
      name:[
        {required:true,message:"不为空"},
        {pattern:nameRegExp,message:"收货人格式不正确"}
      ],
      phone:[
        {required:true,message:"不为空"},
        {pattern:phoneRegExp,message:"手机号不正确"}
      ],
      provinceName: {required:true,message:"不为空"},
      address: {required:true,message:"请输入详细地址"},
    }
    const validator=new Schema(rules)
    return new Promise((resolve)=>{
      validator.validate(params,(errors)=>{
        if(errors){
          wx.showToast({
            title: errors[0].message,
            icon:"none"
          })
          resolve({valid:false})
        }else{
          resolve({valid:true})
        }
      })
    })
  },
  // 省市区选择
  onAddressChange(event) {
    const [provinceCode, cityCode, districtCode] = event.detail.code
    const [provinceName, cityName, districtName] = event.detail.value
    // 存储省市区对应的编码
    this.setData({
      provinceCode,
      cityCode,
      districtCode,
      provinceName,
      cityName,
      districtName
    })
  },
 // 获取当前位置
  async onLocation() {
    const {
      latitude,
      longitude, name
    } = await wx.chooseLocation()
    // 调用接口
    this.qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: (res) => {
        // 获取省市区 以及编码
        const {
          adcode,
          province,
          city,
          district
        } = res.result.ad_info
        // 获取街道和门牌
        const {
          street,
          street_number
        } = res.result.address_component
        // 获取标准地址
        const {
          standard_address,
        } = res.result.formatted_addresses
        //对获取的数据格式化

        this.setData({
          // 省
          provinceName: province,
          // 省 前2位有值,后4为0
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),
          // 市
          cityName: city,
          // 市 前4位有值,后面2位0
          cityCode: adcode.replace(adcode.substring(4), '00'),
          // 区
          districtName: district,
          // 区 全 / 有无区县 因此末尾加上
          districtCode: district && adcode,
          // 组织详细地址
          address: street + street_number + name,
          // 组织完整地址
          fullAddress: standard_address + name,
        })
      }

    });
  },
 
  async onLocationa() {
    const {
      authSetting
    } = await wx.getSetting()
    if (authSetting['scope.userLocation'] === false) {
      wx.showModal({
        title: '授权提示',
        content: '需要获取当前地址位置,请授权',
        showCancel: "true",
        complete: async (res) => {
          if (res.cancel) {
            wx.showToast({
              title: '拒绝授权',
              icon: "error"
            })
          }
          if (res.confirm) {
            const {
              authSetting
            } = await wx.openSetting()
            if (authSetting['scope.userLocation'] === true) {
              this.onLocation()
            } else {
              wx.showToast({
                title: '拒绝授权',
                icon: "error"
              })
            }

          }
        }
      })
    } else {
      try {
        const {
          latitude,
          longitude
        } = await wx.getLocation()


      } catch (error) {
        wx.showToast({
          title: '获取失败,稍后重试',
          icon: "error"
        })
      }
    }

  },
})